﻿import com.mochimedia.ui.*;

/**
 * ...
 * @author Geoff
 */
class com.mochimedia.ui.EventDispatcher 
{
    
    private var _listeners:Object;
    
    public function EventDispatcher () {
        
    }
    
    private function init ():Void {
        
        _listeners = { };
        
    }
    
    //
    //
    public function addEventListener (eventType:String, callbackObject:Object, callbackMethod:Function):Void {

        var self:Object = this;
        
        if (_listeners == undefined) _listeners = { };
   
        if (_listeners[eventType] == undefined) _listeners[eventType] = [];
                
        _listeners[eventType].push(new Event(eventType, callbackObject, callbackMethod));

    }
    
    //
    //
    public function removeEventListener (eventType:String, callbackObject:Object, callbackMethod:Function):Void {
        
        var listeners:Array = _listeners[eventType];
        var e:Event;
        
        for (var i:Number = listeners.length - 1; i >= 0; i--) { 
            
            e = Event(listeners[i]);
            if (e.callbackObj == callbackObject && e.callbackMethod == callbackMethod) listeners.splice(i, 1);
            
        }

    }
    
    //
    //
    public function dispatchEvent (eventType:String):Void {
        
        var listeners:Array = _listeners[eventType];
        var e:Event;

        if (listeners != undefined && listeners.length > 0) {
            
            for (var i:Number = listeners.length - 1; i >= 0; i--) {
                
                e = Event(listeners[i]);
                if (e.callbackObj == undefined) listeners.splice(i, 1);
                e.dispatch(this);
                
            }
            
        }
        
    }
    
}